//require our websocket library
var WebSocketServer = require("ws").Server;

//creating a websocket server at port 9090
var wss = new WebSocketServer({ port: 9090 });

//all connected to the server users
var users = {};

//when a user connects to our sever
wss.on("connection", function (connection) {
  //when server gets a message from a connected user
  connection.on("message", function (message) {
    let data;
    //accepting only JSON messages
    try {
      data = JSON.parse(message);
    } catch (e) {
      data = {};
    }

    const { type, name } = data;
    const userConn = users[name];
    switch (type) {
      case "login": // 用户登录
        if (userConn != null) {
          //如果用户名已被使用，则关闭之前的连接
          userConn.close();
        }
        // 重新设置用户为当前连接
        connection.name = name;
        users[name] = connection;
        sendTo(connection, {
          type: "onLogin",
          name: connection.name,
        });
        break;
      case "offer": // 邀请他人
        console.log(connection.name, "发送邀请给某用户", name);
        // 获取呼叫对象的连接
        if (userConn != null) {
          // 通过呼叫对象的连接告知对方
          sendTo(userConn, {
            type: "onOffer",
            offer: data.offer,
            name: connection.name, //当前连接作为对方
          });
        }
        break;
      case "answer": // 应答某用户
        console.log(connection.name, "发送应答给某用户", name);
        // 对方是否连接
        if (userConn != null) {
          // 通知对方客户端已应答
          sendTo(userConn, {
            type: "onAnswer",
            answer: data.answer,
            name: connection.name, //当前连接作为对方
          });
        }
        break;
      case "candidate": // ICE候选发送他人
        console.log(connection.name, "发送候选给某用户", name);
        if (userConn != null) {
          sendTo(userConn, {
            type: "onCandidate",
            candidate: data.candidate,
            name: connection.name, //当前连接作为对方
          });
        }
        break;
      case "leave": // 挂断他人
        console.log(connection.name, "挂断某用户", name);
        if (userConn != null) {
          sendTo(userConn, {
            type: "onLeave",
            name: connection.name, //当前连接作为对方
          });
        }
        break;
    }
  });

  connection.on("close", function () {
    if (connection.name) {
      delete users[connection.name];
    }
  });
});

function sendTo(connection, message) {
  connection.send(JSON.stringify(message));
}
